package com.old.nsi_class.api;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nsi.util.PropertiesUtil;
import com.old.model.Model;
import com.old.nsi_class.DB.Course_DB;
import com.old.nsi_class.DB.DateUtils;
import com.old.nsi_class.common.payment.WechatPaymentUtil;
import com.nsi.util.MailUtil;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

@WebServlet("/WechatPaymentNotify")
public class WechatPaymentNotify extends HttpServlet {

    private Model model = new Model();
    String NowTime = DateUtils.NowDay();

    private static final long serialVersionUID = -7114177791464988500L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

//    	被动接受微信支付结果通知
        System.out.println("WechatPaymentNotify 接受微信支付结果通知 开始执行---");
        //接受微信发送的参数
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(
                new InputStreamReader((ServletInputStream) request.getInputStream(), "utf-8"));
        String temp;
        while ((temp = br.readLine()) != null) {
            sb.append(temp);
        }
        br.close();
        System.out.println(sb.toString());

        String strxml = sb.toString();

        //解析 XML
        strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");
        if (null == strxml || "".equals(strxml)) {
            System.err.println("Payment_api:微信支付第一步，解析微信返回XML 失败");
        }
        Map m = new HashMap();
        InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
        SAXBuilder builder = new SAXBuilder();
        Document doc = null;
        try {
            doc = builder.build(in);
        } catch (JDOMException e1) {
            e1.printStackTrace();
        }
        org.jdom.Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while (it.hasNext()) {
            org.jdom.Element e = (org.jdom.Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if (children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                //获取子结点的xml
                v = WechatPaymentUtil.getChildrenText(children);
            }
            m.put(k, v);
        }
        //关闭流
        in.close();
        //值的位置：Map m

        //   XML取值
        String result_code = (String) m.get("result_code");
        String total_fee = (String) m.get("total_fee");
        String transaction_id = (String) m.get("transaction_id");
        String out_trade_no = (String) m.get("out_trade_no");

        String attach = (String) m.get("attach");
        String[] split = attach.split("-");
        String ClassId = split[0];
        String UserMail = split[1];

        String resXml = "";
        String adminEmail = PropertiesUtil.getProperty("admin.email");

        //判断是否支付成功
        if (result_code.equals("FAIL")) {
//			支付失败		
            model.commonLog("微信支付", "微信支付通知：失败！！！", NowTime, "微信订单号：" + transaction_id, "商户订单号:" + out_trade_no, attach);
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[微信通知结果为失败]]></return_msg>" + "</xml> ";
        } else {
//			支付成功
            model.commonLog("微信支付", "微信支付通知：成功", NowTime, "微信订单号：" + transaction_id, "商户订单号:" + out_trade_no, attach);

//			支付成功：发送通知邮件
            try {
                MailUtil.SendNotifyMail(adminEmail, "微信支付成功: " + total_fee + "-" + UserMail + " ");
            } catch (Exception e) {
                e.printStackTrace();
            }

//			业务逻辑
//			先判断有没有执行过？
            String sql = "selcet * from nsi_course_user WHERE `ClassId`='" + ClassId + "' AND `UserMail`='" + UserMail + "';";
            int j = Course_DB.count(sql);
            if (j <= 1) {
//				业务代码-未执行过：success
                String sql02 = "insert nsi_course_user (ClassId,UserMail) values ('" + ClassId + "','" + UserMail + "'); ";


                int i = Course_DB.insert02(sql02);
                if (i == 1) {
                    //业务执行成功
                    model.commonLog("微信支付", "微信支付-业务执行：成功", NowTime, "微信订单号：" + transaction_id, "商户订单号:" + out_trade_no, attach);

//					业务执行成功：发送通知邮件
                    try {
                        MailUtil.SendNotifyMail(adminEmail, "微信支付(2)-业务执行成功: " + total_fee + "-" + UserMail + " ");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    //业务执行失败
                    model.commonLog("微信支付", "微信支付-业务执行：失败！！！", NowTime, "微信订单号：" + transaction_id, "商户订单号:" + out_trade_no, attach);
                }
//				业务代码执行过:
            } else {
                model.commonLog("微信支付", "微信支付通知：微信重复发送通知！！", NowTime, "微信订单号：" + transaction_id, "商户订单号:" + out_trade_no, attach);
            }

            resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
        }
//		发送结果

        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();

    }
}
